<template>
  <div class="profile-view">
    <h1>个人中心</h1>
    
    <el-card class="profile-card">
      <template #header>
        <div class="card-header">
          <span>个人信息</span>
          <!-- <el-button type="primary" size="small" @click="isEditing = true" v-if="!isEditing">
            编辑资料
          </el-button> -->
        </div>
      </template>
      
      <div v-if="!isEditing" class="profile-info">
        <div class="info-item">
          <span class="label">用户名：</span>
          <span>{{ userStore.user?.username || '未设置' }}</span>
        </div>
        <div class="info-item">
          <span class="label">邮箱：</span>
          <span>{{ userStore.user?.email || '未设置' }}</span>
        </div>
        <div class="info-item">
          <span class="label">注册时间：</span>
          <span>{{ formatDate(userStore.user?.createdAt) }}</span>
        </div>
      </div>
      
      <el-form 
        v-else 
        ref="profileForm" 
        :model="profileData" 
        :rules="rules" 
        label-position="top"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="profileData.username" />
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="profileData.email" />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="updateProfile" :loading="isSubmitting">
            保存
          </el-button>
          <el-button @click="cancelEdit">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- <el-card class="profile-card">
      <template #header>
        <div class="card-header">
          <span>修改密码</span>
        </div>
      </template>
      
      <el-form 
        ref="passwordForm" 
        :model="passwordData" 
        :rules="passwordRules" 
        label-position="top"
      >
        <el-form-item label="当前密码" prop="currentPassword">
          <el-input 
            v-model="passwordData.currentPassword" 
            type="password" 
            show-password
          />
        </el-form-item>
        
        <el-form-item label="新密码" prop="newPassword">
          <el-input 
            v-model="passwordData.newPassword" 
            type="password" 
            show-password
          />
        </el-form-item>
        
        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input 
            v-model="passwordData.confirmPassword" 
            type="password" 
            show-password
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="changePassword" :loading="isChangingPassword">
            修改密码
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
     -->
    <el-card class="profile-card">
      <template #header>
        <div class="card-header">
          <span>账号安全</span>
        </div>
      </template>
      
      <div class="security-actions">
        <el-button type="danger" @click="confirmLogout">
          退出登录
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useUserStore } from '../stores/user'
import { ElMessage, ElMessageBox } from 'element-plus'
// import { authService } from '../services/auth'

const userStore = useUserStore()
const isEditing = ref(false)
const isSubmitting = ref(false)
const isChangingPassword = ref(false)
const profileForm = ref(null)
const passwordForm = ref(null)

const profileData = reactive({
  username: '',
  email: ''
})

const passwordData = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}

const validatePass = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== passwordData.newPassword) {
    callback(new Error('两次输入密码不一致'))
  } else {
    callback()
  }
}

const passwordRules = {
  currentPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, validator: validatePass, trigger: 'blur' }
  ]
}

onMounted(() => {
  if (userStore.isLoggedIn && !userStore.user) {
    userStore.fetchUserProfile()
  }
  
  if (userStore.user) {
    profileData.username = userStore.user.username || ''
    profileData.email = userStore.user.email || ''
  }
})

const formatDate = (dateString) => {
  if (!dateString) return '未知'
  
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const cancelEdit = () => {
  isEditing.value = false
  profileData.username = userStore.user?.username || ''
  profileData.email = userStore.user?.email || ''
}

const updateProfile = async () => {
  if (!profileForm.value) return
  
  await profileForm.value.validate(async (valid) => {
    if (valid) {
      isSubmitting.value = true
      try {
        // 这里应该调用API更新用户资料
        // 模拟API调用
        await new Promise(resolve => setTimeout(resolve, 1000))
        
        // 更新本地用户信息
        if (userStore.user) {
          userStore.user.username = profileData.username
          userStore.user.email = profileData.email
        }
        
        ElMessage.success('个人资料更新成功')
        isEditing.value = false
      } catch (error) {
        console.error('更新个人资料失败:', error)
        ElMessage.error('更新个人资料失败')
      } finally {
        isSubmitting.value = false
      }
    }
  })
}

const changePassword = async () => {
  if (!passwordForm.value) return
  
  await passwordForm.value.validate(async (valid) => {
    if (valid) {
      isChangingPassword.value = true
      try {
        // 这里应该调用API修改密码
        // 模拟API调用
        await new Promise(resolve => setTimeout(resolve, 1000))
        
        ElMessage.success('密码修改成功')
        passwordData.currentPassword = ''
        passwordData.newPassword = ''
        passwordData.confirmPassword = ''
        passwordForm.value.resetFields()
      } catch (error) {
        console.error('修改密码失败:', error)
        ElMessage.error('修改密码失败')
      } finally {
        isChangingPassword.value = false
      }
    }
  })
}

const confirmLogout = () => {
  ElMessageBox.confirm(
    '确定要退出登录吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    userStore.logout()
  }).catch(() => {})
}
</script>

<style scoped>
.profile-view {
  max-width: 800px;
  margin: 0 auto;
}

.profile-card {
  margin-bottom: 2rem;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.profile-info {
  padding: 1rem 0;
}

.info-item {
  margin-bottom: 1rem;
  display: flex;
}

.label {
  font-weight: bold;
  width: 100px;
}

.security-actions {
  display: flex;
  justify-content: flex-end;
}

@media (max-width: 768px) {
  .info-item {
    flex-direction: column;
  }
  
  .label {
    margin-bottom: 0.5rem;
  }
}
</style>